using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Lu62Viewer
{
    public class MySegmentNode : MyNode
    {
        private Color segmentColorNode = Color.Maroon;        

        private void init()
        {
            ForeColor = segmentColorNode;
        }

        public MySegmentNode(string _segmentText, char _separator, int _nameLenght, int _startPos) : this(_segmentText, _separator, _nameLenght)
        {
            Pos = _startPos;
            init();
        }

        public MySegmentNode(string _segmentText, char _separator, int _nameLenght) 
        {
            m_segmentNameLenght = _nameLenght;
            m_separator = _separator;
            Text = getFirstField(_segmentText);
            Lenght = _segmentText.Length;
            int currentPos = 1;
            int startPos = 0;
            bool checkedFirst = false;
            foreach (char _c in _segmentText)
            {
                if (_c == m_separator)
                {
                    if (!checkedFirst)
                    {
                        startPos = currentPos;
                        checkedFirst = true;
                    }
                    else
                    {
                        int lenght = (currentPos) - startPos;
                        string fieldText = _segmentText.Substring(startPos, lenght);
                        startPos = currentPos;
                        MyFieldNode n = new MyFieldNode(fieldText.Replace(m_separator, ' '), currentPos);                        
                        Nodes.Add(n);
                    }
                }
                currentPos++;
            }
            init();
        }

        public const string SegmentErrorLenghtName = "Segment name empty";

        private string getFirstField(string _lu62)
        {
            if (_lu62.IndexOf(m_separator) == -1)
                throw new ArgumentException(string.Format("Il separatore '{0}' non e' corretto", m_separator));
            string field = _lu62.Substring(0, _lu62.IndexOf(m_separator));
            try
            {
                return field.Substring(field.Length - m_segmentNameLenght, m_segmentNameLenght);
            }
            catch 
            {
                return SegmentErrorLenghtName;
            }
        }        

        private int m_segmentNameLenght;
        private char m_separator;    
    }
}
